package com.cn.sl.server.config

import com.zaxxer.hikari.HikariDataSource
import net.ttddyy.dsproxy.listener.logging.SLF4JLogLevel
import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder
import org.hibernate.engine.jdbc.internal.FormatStyle
import org.hibernate.engine.jdbc.internal.Formatter
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.util.StringUtils
import javax.sql.DataSource


@Configuration
class DataSourceConfig {
    var logger: Logger = LoggerFactory.getLogger(DataSourceConfig::class.java)


    /**
     * 主数据源配置
     *
     * @return DataSource
     */
    @Primary
    @Bean(name = ["dataSource"])
    fun dataSource(dataSourceProperties: DataSourceProperties): DataSource {
        // 创建 HikariDataSource 对象
        return createHikariDataSource(dataSourceProperties)
    }

    private fun createHikariDataSource(properties: DataSourceProperties): DataSource {
        // 创建 HikariDataSource 对象
        val dataSource = properties.initializeDataSourceBuilder().type(
            HikariDataSource::class.java
        ).build()
        // 设置线程池名
        if (StringUtils.hasText(properties.name)) {
            dataSource.poolName = properties.name
        }

        val formatter: Formatter = FormatStyle.BASIC.formatter
        return ProxyDataSourceBuilder.create(dataSource)
            .formatQuery(formatter::format)
            // 包含参数信息
            .multiline()
            .logQueryBySlf4j(SLF4JLogLevel.INFO)
            .buildProxy()!!
    }
}

@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
data class SqlLogConfig(
    var sqlLogLevel: SLF4JLogLevel = SLF4JLogLevel.INFO
)